package templates

import (
	_const "gitee.com/lstack_light/go-light/internal/pkg/global"
	"log"
	"os"
	"strings"
	"text/template"
)

/**
  @author: light
  @since: 2023/9/3
  @desc: 业务层实现模板
*/

var _ Template = &ServiceImpl{}

type ServiceImpl struct {
	Receiver *Receiver
	TemplateParams
}

func (s *ServiceImpl) Execute(eventType _const.TemplateEventType) error {
	switch eventType {
	case _const.InitEvent:
		return s.Init()
	case _const.GenerateEvent:
		return s.Generate()
	}
	return nil
}

func (s *ServiceImpl) Init() error {
	serviceImplData := []byte("package impl\n\nimport (\n\t\"gitee.com/lstack_light/go-light/pkg/server/respData\"\n\t\"strconv\"\n\t\"{{.Module}}/internal/model/bto\"\n)\n\nvar (\n\t{{.Name}}ServiceImpl = &{{.Self}}{}\n)\n\ntype {{.Self}} struct {\n}\n\nfunc ({{.SelfPrefix}} *{{.Self}}) FindAll() *respData.Response {\n\tresult := struct {\n\t\tItems []bto.{{.Name}} `json:\"items\"`\n\t\tTotal int             `json:\"total\"`\n\t}{\n\t\tItems: []bto.{{.Name}}{},\n\t\tTotal: 0,\n\t}\n\treturn respData.SuccessResponse(result, \"操作成功\")\n}\n\nfunc ({{.SelfPrefix}} *{{.Self}}) FindOne(param *bto.{{.Name}}) *respData.Response {\n\treturn respData.SuccessResponse(param, \"操作成功\")\n}\n\nfunc ({{.SelfPrefix}} *{{.Self}}) CreateOne(param *bto.{{.Name}}) *respData.Response {\n\treturn respData.SuccessResponse(param, \"操作成功\")\n}\n\nfunc ({{.SelfPrefix}} *{{.Self}}) UpdateOne(param *bto.{{.Name}}) *respData.Response {\n\treturn respData.SuccessResponse(param, \"操作成功\")\n}\n\nfunc ({{.SelfPrefix}} *{{.Self}}) DeleteOne(param *bto.{{.Name}}) *respData.Response {\n\treturn respData.SuccessResponse(\"已删除：\"+strconv.Itoa(param.Id), \"操作成功\")\n}")
	err := os.WriteFile(s.TemplateName, serviceImplData, 0644)
	if err != nil {
		log.Fatal("创建业务层实现模板文件失败：", err)
		return err
	}
	return s.Receiver.next.Execute(_const.InitEvent)
}

func (s *ServiceImpl) Generate() error {
	file, createErr := os.Create(s.OutputFile)
	if createErr != nil {
		log.Fatal(createErr)
		return createErr
	}
	// 读取模板文件
	tmpl, tempErr := template.ParseFiles(s.TemplateName)
	if tempErr != nil {
		log.Fatal("解析业务层实现模板失败：", tempErr)
		return tempErr
	}
	// 定义引用变量
	type Temp struct {
		Name       string
		Module     string
		Self       string
		SelfPrefix string
	}
	temp := Temp{
		Name:       s.Name,
		Module:     s.Module,
		Self:       strings.ToLower(s.Name) + "ServiceImpl",
		SelfPrefix: strings.ToLower(s.Name)[0:1],
	}
	// 执行模板填充并写入输出文件
	err := tmpl.Execute(file, temp)
	if err != nil {
		log.Fatal(err)
		return err
	}
	// 删除模板文件
	_ = os.RemoveAll(s.TemplateName)
	log.Println("Go文件已生成：", s.OutputFile)
	return s.Receiver.next.Execute(_const.GenerateEvent)
}
